##server.py
from socket import *
from sys import *
from monocipher import *
from polycipher import *
from homophonic import *
from polygram import *
import random

if len(argv) < 3:
    print("error: run 'python server.py outputfile mode'")
    exit(0)

random.seed(5)

HOST = ''
PORT = 8005
FILE = argv[1]
SEQ = random.randint(1000000, 2000000)

if argv[2] == '0':
    cipher = MonoCipher()
elif argv[2] == '1':
    cipher = PolyCipher()
elif argv[2] == '2':
    cipher = HomoPhonicCipher()
elif argv[2] == '3':
    cipher = PolygramCipher('4')
else:
    print 'error: cyphermode argument not recognized'
    exit(0)

file = open(FILE, 'a')


server = socket(AF_INET, SOCK_STREAM)    
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

server.bind((HOST, PORT))
server.listen(1)
print 'listening...'

conn, addr = server.accept()
print 'connected to ', addr

while 1:
    message = conn.recv(1024)

    if message:
        if argv[2] != '0':
            decrypted = message[:len(str(SEQ))] + cipher.decrypt(message[len(str(SEQ)):])
        else:
            decrypted = cipher.decrypt(message)
        
        file = open(FILE, 'a')
        file.write(decrypted + '\n')
        file.close()
        
        print 'recieved: ' + message
        print 'decrypted: ' + decrypted
        print ''
        
        SEQ = random.randint(1000000, 2000000)

    elif not message:
        break

conn.close()
